package com.glory.brepda.activity.recipe;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.UpImageAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.customView.CustomLoadingDialog;
import com.glory.brepda.entity.RecipeImageEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import butterknife.BindView;

public class SolderJointUpImageActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvUpImage)
    TextView tvUpImage;
    @BindView(R.id.rvImageList)
    RecyclerView rvImageList;
    @BindView(R.id.tvEqpID)
    TextView tvEqpID;
    @BindView(R.id.tvRecipeName)
    TextView tvRecipeName;

    private UpImageAdapter mUpImageAdapter;
    private ProgressDialog mProgressDialog = null;
    private String eqpID = "";
    private String recipeName = "";
    private String ID = "";
    private String mFilePath = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_image_up;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        eqpID = bundle.getString("EQPID");
        recipeName = bundle.getString("RecipeName");
        ID = bundle.getString("ID");
        String title = bundle.getString("TITLE");
        tvTitle.setText(title);
        tvEqpID.setText(eqpID);
        tvRecipeName.setText(recipeName);
        if (title.equals("查看图片")){
            tvUpImage.setVisibility(View.GONE);
            tvBaseSubmit.setVisibility(View.GONE);
            String bdcode = bundle.getString("BDCODE");
            getImageUri(ID,bdcode);
        }

        setMainLayout(llMain);

        mUpImageAdapter = new UpImageAdapter(null,false);
        mUpImageAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mUpImageAdapter.isFirstOnly(true);
        initRecyclerView(rvImageList, this);
        rvImageList.setAdapter(mUpImageAdapter);
        mUpImageAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmAndCancelDialog(MyApp.app, "是","否", "是否删除？", () -> {
                    mUpImageAdapter.remove(position);
                },()->{});
                tipDialog.show(getSupportFragmentManager(),"DIALOG");
                return false;
            }
        });


        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    @Override
    protected void initData() {
        tvUpImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    CharSequence[] items = {"拍照", "图库"};
                    new AlertDialog.Builder(SolderJointUpImageActivity.this)
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    switch (which) {
                                        // 选择了拍照
                                        case 0:
                                            onJurisdiction();
                                            break;
                                        case 1:
                                            Intent intent1 = new Intent(Intent.ACTION_PICK,
                                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                            startActivityForResult(intent1, 13);
                                            break;
                                    }
                                }
                            }).show();
            }
        });

        tvBaseSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoading();
                if (mUpImageAdapter.getData().size() == 0){
                    hideLoading();
                    showToast("请选择图片",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<Object>> callBack = new FreeUI_EntityCallBack<BaseResponseBean<Object>>
                        (new TypeToken<BaseResponseBean<Object>>() {
                        }.getType()) {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<Object>> response) {
                        hideLoading();
                        if (response.body().isSuccess(SolderJointUpImageActivity.this,false,getSupportFragmentManager())){
                            showToast("上传成功",true);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            }, 1000);
                        }
                    }
                    @Override
                    public void onError(Response<BaseResponseBean<Object>> response) {
                        super.onError(response);
                        hideLoading();
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("recipeId",ID);
                map.add("img", new JsonParser().parse(new Gson().toJson(mUpImageAdapter.getData())).getAsJsonArray());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        NetUtils.requestPostNet("EAP.UploadRecipeImg", "UploadRecipeImg", SolderJointUpImageActivity.this, map, callBack);
                    }
                }, 500);

            }
        });
    }

    private void getImageUri(String recipeName, String bdcode) {
        FreeUI_EntityCallBack<BaseResponseBean<RecipeImageEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<RecipeImageEntity>>
                (new TypeToken<BaseResponseBean<RecipeImageEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<RecipeImageEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(SolderJointUpImageActivity.this,true,getSupportFragmentManager())){
                    ArrayList<String> strings = new ArrayList<>();
                    if (!response.body().getResponse().getBody().getBdCodeUrl().equals("")){
                        strings.add(response.body().getResponse().getBody().getBdCodeUrl());
                    }
                    strings.addAll(response.body().getResponse().getBody().getUrl());
                    mUpImageAdapter.setNewData(strings);
                }else {
                    finish();
                }
            }
            @Override
            public void onError(Response<BaseResponseBean<RecipeImageEntity>> response) {
                super.onError(response);

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("recipeId",recipeName);
        map.addProperty("BD_CODE",bdcode);
        NetUtils.requestPostNet("GetRecipeImg", "GetRecipeImg", SolderJointUpImageActivity.this, map, callBack);

    }

    private void dispatchTakePictureIntent() {

        mFilePath = Environment.getExternalStorageDirectory().getPath()+"/" + "mytest.png";
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mUri = Uri.fromFile(new File(mFilePath));
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(openCameraIntent, 1);
    }

    public void choosePhoto() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),13);
        } else {
            Intent intent = new Intent();
            // intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//支持多选图片
            intent.setType("image/*");
            intent.setAction("android.intent.action.GET_CONTENT");
            intent.addCategory("android.intent.category.OPENABLE");
            startActivityForResult(intent, 13);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {

            Uri uri1 = Uri.fromFile(new File(mFilePath));
            ContentResolver cr = this.getContentResolver();
            try {
                InputStream is = cr.openInputStream(uri1);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize =3;
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
//                mUpImageAdapter.addData(bitmapToBase64(rotaingImageView(90,bitmap)));
                mUpImageAdapter.addData(bitmapToBase64(bitmap));
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        if (requestCode == 13){
            if (data == null || data.getData() == null){
                showToast("未选择图片",false);
                return;
            }
            Uri imageUri = data.getData();
            ContentResolver cr = this.getContentResolver();
            try {
                InputStream is = cr.openInputStream(imageUri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize =3;
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
                mUpImageAdapter.addData(bitmapToBase64(rotaingImageView(0,bitmap)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }

    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private void onJurisdiction() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
                return;
            } else {
                dispatchTakePictureIntent();
            }
        } else {
            dispatchTakePictureIntent();
        }
    }
    public void showLoading() {
        // region 正在加载中,请稍后
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        // 正在加载中,请稍后
        mProgressDialog = ProgressDialog.show(this, "提示", "正在上传中···");
    }
    public void hideLoading() {
        // 取消进度框
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
}
